package com.base.core.utils;

import com.base.api.UploadFileController;
import com.base.config.UploadConfig;
import com.base.core.model.ApiRes;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author win10
 */
public class UploadUtil {

    private static final Logger logger = LoggerFactory.getLogger(UploadFileController.class);

    private static final String[] image = {".gif", ".jpg", ".jpeg", ".png", ".bmp", ".pdf"};


    public static String uploadMultipartFileToTencentCOS(MultipartFile file) {
        // 获得文件名:
        String fileName = file.getOriginalFilename();
        // 获得文件的扩展名(包含.):
        // String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        // 新的文件名
        String newFileName = System.currentTimeMillis() + "_" + fileName;
        COSClient cosClient = null;
        try {

            // 1 初始化用户身份信息（secretId, secretKey
            COSCredentials cred = new BasicCOSCredentials(UploadConfig.secretId, UploadConfig.secretKey);

            // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
            // clientConfig中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者接口文档 FAQ 中说明。
            ClientConfig clientConfig = new ClientConfig(new Region(UploadConfig.regionName));

            // 3 生成 cos 客户端。
            cosClient = new COSClient(cred, clientConfig);

            // 指定要上传到的存储桶   bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
            String bucketName = UploadConfig.bucketName;

            // 指定要上传到 COS 上对象键
            String key = UploadConfig.keyPrefix + newFileName;

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream(), new ObjectMetadata());
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

            //网络资源访问路径
            String path = UploadConfig.accessPath + UploadConfig.keyPrefix + newFileName;

            logger.info("文件上传成功，路径为：{}", path);

           return path;

        } catch (Exception e) {
            logger.error("文件上传异常：{}", e);
            return "";

        } finally {
            //关闭客户端
            if (cosClient != null) {
                cosClient.shutdown();
            }
        }
    }
}
